package com.witmore.skyline.web.controller;

import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 提供服务状态检查接口
 */
@Slf4j
@RestController
@RequestMapping("/actuator/health")
public class HealthController {

    /**
     * 简单的健康检查接口
     * @return 服务状态
     */
    @GetMapping("/check")
    public ResponseResult<String> healthCheck() {
        try {
            return ResponseResult.success("服务运行正常");
        } catch (Exception e) {
            log.error("健康检查异常", e);
            return ResponseResult.fail(500,"服务检查异常");
        }
    }

    /**
     * 详细的服务状态信息
     * @return 详细状态信息
     */
    @GetMapping("/status")
    public ResponseResult<Map<String, Object>> serviceStatus() {
        try {
            Map<String, Object> status = new HashMap<>();

            // 基本信息
            status.put("service_name", "witmore-skyline-master-web");
            status.put("version", "1.0.0-SNAPSHOT");
            status.put("status", "运行正常");
            status.put("check_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            // 运行时间
            RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
            long uptime = runtimeBean.getUptime();
            status.put("uptime", formatUptime(uptime));
            status.put("uptime_ms", uptime);

            return ResponseResult.success(status);
        } catch (Exception e) {
            log.error("获取服务状态异常", e);
            return ResponseResult.fail(500,"获取服务状态失败");
        }
    }

    /**
     * 格式化运行时间
     */
    private String formatUptime(long uptimeMs) {
        long seconds = uptimeMs / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (days > 0) {
            return String.format("%d天 %d小时 %d分钟", days, hours % 24, minutes % 60);
        } else if (hours > 0) {
            return String.format("%d小时 %d分钟", hours, minutes % 60);
        } else if (minutes > 0) {
            return String.format("%d分钟 %d秒", minutes, seconds % 60);
        } else {
            return String.format("%d秒", seconds);
        }
    }
}
